package br.com.vagacerta.controller;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import br.com.vagacerta.dao.UsuarioDAO;
import br.com.vagacerta.modelo.Usuario;


@Controller
public class LoginController {
	
	private final UsuarioDAO dao;
	
	
	@Autowired
	public LoginController(UsuarioDAO dao) {
		this.dao = dao;
	}
	
	
	@RequestMapping("loginForm")
	public String loginForm() {
		return "login";
	}
	
	@RequestMapping("efetuaLogin")
	public String efetuaLogin(String login, String password, HttpSession session){
		
		Usuario usuario = new Usuario();
		usuario.setLogin(login);
		usuario.setPassword(password);
		
		Usuario user = new Usuario();
		user = dao.getUsuario(usuario);
		
		if (user.getCodUsuario() != 0) {
			session.setAttribute("usuarioLogado", user);
			session.setAttribute("horaEntrada", this.formataDataAtual());
			return "home";
		}
		return "redirect:loginForm";
	}
	
	@RequestMapping("logout")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:loginForm";
		
	}
	
	private String formataDataAtual () {
		
		Calendar c = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("EE,dd,MMMM,yyyy");
		String data = sdf.format(c.getTime());
		
		String[] valoresData = data.split(",");
		 String retornoData = valoresData[0].toUpperCase() + ", " + valoresData[1] + " de " + valoresData[2] + " de " + valoresData[3] + ".";
		 return retornoData;
	}


}
